package com.gopay.cashier.service.cloud.impl;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import com.gopay.cashier.common.exception.WebException;
import com.gopay.cashier.domain.bean.LoginUser;
import com.gopay.cashier.service.cloud.CloudLoginService;
import com.gopay.cashier.web.controller.EntryController;
import com.gopay.common.constants.cust.UserInfoConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.constants.txncd.IntTxnCd;
import com.gopay.common.domain.UserInfo;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.domain.cust.CustCorpInfo;
import com.gopay.common.user.manager.CustCorpInfoQueryManager;
import com.gopay.common.user.manager.UserInfoQueryManager;
import com.gopay.remote.user.UserAdmitRemoteService;
import com.gopay.remote.vo.UserAdmitRes;

/**
 * 网关的充值和网关支付 ，云账户的需要：实现登录,为了不影响原有交易，拷贝一份出来单独处理
 * ZhangZG
 * 2016年1月28日 
 * www.gopay.com.cn Inc.All rights reserved.
 */
@Service("cloudLoginService")
public class CloudLoginServiceImpl implements CloudLoginService{

	private final static Log logger = LogFactory.getLog(CloudLoginServiceImpl.class);
	
	@Resource(name="custCorpInfoQueryManager")
	private CustCorpInfoQueryManager custCorpInfoQueryManager;
	
	@Resource(name="userInfoQueryManager")
	private UserInfoQueryManager userInfoQueryManager;
	
    @Resource(name="admitService")
    private UserAdmitRemoteService userService;
   
    /**收银台跳转地址**/
    public static final String CASHIER_URL="CASHIER_URL";
    
    /**AUTH验证跳转地址**/
    public static final String CAS_SERVER_URL="CAS_SERVER_URL";
    /**spring-config-mvc.xml 中获取URl**/
    @Resource(name = "cloudUrlMap")
    private Map<String, String> cloudUrlMap;
    
	@Override
	public boolean login(HttpServletRequest request,CpsGenMainOrder order,String key,ModelAndView mav) throws WebException {
		if(request.getSession().getAttribute(order.getGopayOrderId())==null&&
    	(IntTxnCd._00500.value.equals(order.getGopayIntTxnCd())||IntTxnCd._00100.value.equals(order.getGopayIntTxnCd()))
    	)
		{
			logger.error("进入cloud.111.....");
    		mav.setViewName("cloud/loginAuth");
    		String userId=getUserId(order);
    		if(userId==null){
    			throw new WebException(ProcCodeConstants.PROC_CODE_100E2018);
    		}
    		
    		UserAdmitRes userAdmitRes = userService.enquireAdmit(userId);
    		String token = userAdmitRes.getToken();
    		mav.addObject("token", token);
    		mav.addObject("userId", userId);
    		mav.addObject("authUrl", cloudUrlMap.get(CAS_SERVER_URL));
    		mav.addObject("cashierUrl", cloudUrlMap.get(CASHIER_URL)+"/pay/cloud/order.shtml?"
    				+ "orderId="+order.getGopayOrderId()+"&orderKey="+key);
    		request.getSession().setAttribute(order.getGopayOrderId(), order.getGopayOrderId());
    		return false;
    	}else{
			logger.error("进入cloud.222.....");
    		request.getSession().removeAttribute(order.getGopayOrderId());
    		return true;
    	}
    	
	}

	/**
	 * 获取用户Userid
	 * @param order
	 * @return
	 * @throws WebException
	 */
	private String getUserId(CpsGenMainOrder order) throws WebException {
		CustCorpInfo corp=null;
		if(IntTxnCd._00500.value.equals(order.getGopayIntTxnCd())){
			corp=custCorpInfoQueryManager.get(order.getMainRecvCustId());
		}
		if(IntTxnCd._00100.value.equals(order.getGopayIntTxnCd())){
			corp=custCorpInfoQueryManager.get(order.getPayCustId());
		}
		if(corp==null){
			throw new WebException(ProcCodeConstants.PROC_CODE_100E2018);
		}
		UserInfo userInfo=userInfoQueryManager.getUserInfoByCustIdAndOprId(corp.getCustId(), UserInfoConstants.CORP_ADMIN_CODE);
		this.logger.info("支付/充值的userId="+userInfo.getUserId());
		return userInfo.getUserId();
	}


	@Override
	public boolean checkLogin(LoginUser lu, CpsGenMainOrder order) throws WebException {
		String userId=lu.getUser().getUserId();
		logger.info("当前登录的userId="+userId);
		if(userId.equals(getUserId(order))){
			return true;
		}
		return false;
	}

}
